<!--
 * @Author: 赵克强 huohuo625@163.com
 * @Date: 2023-10-26 16:58:48
 * @LastEditors: 赵克强 huohuo625@163.com
 * @LastEditTime: 2025-04-10 11:09:13
 * @FilePath: \hy-ui\src\views\app\appInfo\components\detail\pageModel\addOrEditModal.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->


<template>
  <div class="addOrEditModalMain">
    <el-dialog
      custom-class="addOrEditModal"
      :title="row ? '编辑' : '新增'"
      :visible.sync="open"
      :before-close="closeConfirm"
      :fullscreen="true"
    >
      <div>
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="基本信息" name="1"
            ><basicInformation
              :openChooseTable="() => (openChooseTable = true)"
              :getChooseTableList="getChooseTableList"
              :closeMOdel="() => (openChooseTable = false)"
              :appId="appId"
              ref="basicInformation"
              v-if="activeName === '1'"
          /></el-tab-pane>
          <el-tab-pane label="列表显示" name="2"
            ><listView
              ref="listView"
              v-if="activeName === '2'"
              :dataConfigOpenFun="dataConfigOpenFun"
              :dataConfigClose="dataConfigClose"
          /></el-tab-pane>
          <el-tab-pane label="查询条件" name="3"
            ><queryCriteria
              ref="queryCriteria"
              v-if="activeName === '3'"
              :row="row"
              :dataConfigOpenFun="searchDataConfigOpenFun"
              :dataConfigClose="searchDataConfigClose"
          /></el-tab-pane>
          <el-tab-pane label="按钮配置" name="4"
            ><buttonConfig
              ref="buttonConfig"
              v-if="activeName === '4'"
              :openChooseTable="() => (openChooseTableForm = true)"
              :getChooseTableList="getChooseTableListForm"
              :closeMOdel="() => (openChooseTableForm = false)"
              :appId="appId"
              :dataConfigOpenFun="buttonConfigOpenFun"
              :dataConfigClose="buttonConfigClose"
          /></el-tab-pane>
          <el-tab-pane label="数据权限" name="5"
            ><dataPower
              ref="dataPower"
              v-if="activeName === '5'"
              :appId="appId"
          /></el-tab-pane>
        </el-tabs>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button
          type="primary"
          @click="handleSubmit"
          style="background: #2f54eb"
          >保存</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      title="选择表"
      :visible.sync="openChooseTable"
      custom-class="ChooseTable"
      width="90%"
      :before-close="() => (openChooseTable = false)"
    >
      <el-tabs v-model="activeName">
        <el-tab-pane label="当前应用" name="1"></el-tab-pane>
        <!-- <el-tab-pane label="公共应用" name="2">公共应用</el-tab-pane> -->
      </el-tabs>
      <div
        style="margin-bottom: 20px; display: flex; justify-content: flex-end"
      >
        <el-input
          placeholder="请输入关键字"
          v-model="queryParams.tableName"
          class="input-with-select"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            type="primary"
            style="background: #2f54eb"
            @click="getChooseTableList"
          ></el-button>
        </el-input>
      </div>
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        v-if="activeName === '1'"
        v-loading="loading"
      >
        <el-table-column label=" " align="center" width="60">
          <template slot-scope="scope">
            <el-radio
              v-model="radio"
              :label="scope.$index"
              @change.native="getCurrentRow(scope.row)"
              >&nbsp;</el-radio
            >
          </template>
        </el-table-column>
        <el-table-column prop="date" label="序号" width="80" align="center">
          <template slot-scope="scope">
            {{
              (queryParams.pageNum - 1) * queryParams.pageSize +
              (scope.$index + 1)
            }}
          </template>
        </el-table-column>
        <el-table-column prop="tableName" label="表名称" align="center">
        </el-table-column>
        <el-table-column prop="remark" label="表描述" align="center">
        </el-table-column>
        <el-table-column
          prop="dataSource"
          label="数据源"
          align="center"
          :formatter="() => '本地数据源'"
        >
        </el-table-column>
        <el-table-column
          prop="entityTableStatus"
          label="实体表状态"
          align="center"
          :formatter="
            (row) =>
              row.entityTableStatus
                ? selectDictLabel(
                    dict.type.pt_app_entity_status,
                    row.entityTableStatus
                  )
                : '--'
          "
        >
        </el-table-column>
      </el-table>
      <div class="pagination">
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getChooseTableList"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="() => (openChooseTable = false)">取 消</el-button>
        <el-button type="primary" @click="handleChooseTableSubmit"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      title="选择表单"
      :visible.sync="openChooseTableForm"
      custom-class="ChooseTable"
      width="90%"
      :before-close="() => (openChooseTableForm = false)"
    >
      <el-tabs v-model="activeName">
        <el-tab-pane label="当前应用" name="4"></el-tab-pane>
        <!-- <el-tab-pane label="公共应用" name="2">公共应用</el-tab-pane> -->
      </el-tabs>
      <div
        style="margin-bottom: 20px; display: flex; justify-content: flex-end"
      >
        <el-input
          placeholder="请输入关键字"
          v-model="queryParamsForm.name"
          class="input-with-select"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            type="primary"
            style="background: #2f54eb"
            @click="getChooseTableListForm"
          ></el-button>
        </el-input>
      </div>
      <el-table
        :data="tableDataForm"
        border
        style="width: 100%"
        v-if="activeName === '4'"
        v-loading="loading"
      >
        <el-table-column label=" " align="center" width="60">
          <template slot-scope="scope">
            <el-radio
              v-model="radioForm"
              :label="scope.$index"
              @change.native="getCurrentRowForm(scope.row)"
              >&nbsp;</el-radio
            >
          </template>
        </el-table-column>
        <el-table-column prop="date" label="序号" width="80" align="center">
          <template slot-scope="scope">
            {{
              (queryParamsForm.pageNum - 1) * queryParamsForm.pageSize +
              (scope.$index + 1)
            }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="表单名称" align="center">
        </el-table-column>
        <el-table-column prop="code" label="表单标识" align="center">
        </el-table-column>
        <el-table-column prop="erModel" label="ER模型" align="center">
        </el-table-column>
        <el-table-column
          prop="entityTableStatus"
          label="表单状态"
          align="center"
          :formatter="
            (row) => selectDictLabel(dict.type.pt_app_enable_status, row.status)
          "
        >
        </el-table-column>
      </el-table>
      <div class="pagination">
        <pagination
          v-show="totalForm > 0"
          :total="totalForm"
          :page.sync="queryParamsForm.pageNum"
          :limit.sync="queryParamsForm.pageSize"
          @pagination="getChooseTableListForm"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="() => (openChooseTableForm = false)"
          >取 消</el-button
        >
        <el-button type="primary" @click="handleChooseTableSubmitForm"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <dataConfigModel
      v-if="dataConfigOpen"
      :dataConfigOpen="dataConfigOpen"
      :dataConfigClose="dataConfigClose"
      :rowData="rowData"
      :appId="appId"
      :handleDataConfigSum="handleDataConfigSum"
    />
    <searchDataConfigModel
      v-if="searchDataConfigOpen"
      :dataConfigOpen="searchDataConfigOpen"
      :dataConfigClose="searchDataConfigClose"
      :rowData="rowSearchData"
      :appId="appId"
      :handleDataConfigSum="handleDataConfigSumSearch"
    />
    <buttonConfigModel
      v-if="buttonConfigOpen"
      :dataConfigOpen="buttonConfigOpen"
      :dataConfigClose="buttonConfigClose"
      :rowData="buttonConfigRow"
      :appId="appId"
      :handleDataConfigSum="buttonConfigSum"
      :pageCode="row.code"
    />
  </div>
</template>

<script>
import basicInformation from "./components/basicInformation.vue";
import listView from "./components/listView.vue";
import queryCriteria from "./components/queryCriteria.vue";
import buttonConfig from "./components/buttonConfig.vue";
import dataConfigModel from "./components/dataConfigModel.vue";
import searchDataConfigModel from "./components/searchDataConfigModel.vue";
import buttonConfigModel from "./components/buttonConfigModel.vue";
import dataPower from "./components/dataPower.vue";
import { listAppInfo } from "@/api/app/electronicForms.js";
import { getOnlineList } from "@/api/app/dataModel/entityModel";
import { appPageModelSave, appPageModelDetail } from "@/api/app/pageModel";
import { uuid } from "vue-uuid";

export default {
  name: "addOrEditModal",
  dicts: ["pt_app_entity_status", "pt_app_enable_status"],
  components: {
    basicInformation,
    listView,
    queryCriteria,
    buttonConfig,
    dataConfigModel,
    dataPower,
    searchDataConfigModel,
    buttonConfigModel,
  },
  props: {
    open: {
      type: Boolean,
      default: false,
    },
    close: {
      type: Function,
      default: () => {},
    },
    getList: {
      type: Function,
      default: () => {},
    },
    row: {
      type: String,
      default: "",
    },
    appId: {
      type: String,
      default: "",
    },
    modelType: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      dataConfigOpen: false,
      searchDataConfigOpen: false,
      activeName: "1",
      openChooseTable: false,
      openChooseTableForm: false,
      queryParamsForm: { tableName: undefined, pageNum: 1, pageSize: 10 },
      radio: "",
      radioForm: "",
      chooseData: {},
      chooseDataForm: {},
      tableDataForm: [],
      queryParams: { tableName: undefined, pageNum: 1, pageSize: 10 },
      loading: false,
      total: 0,
      totalForm: 0,
      rowData: null,
      rowSearchData: null,
      buttonConfigOpen: false,
      buttonConfigRow: null,
    };
  },

  async mounted() {
    if (this.row && !this.modelType) {
      this.activeName = null;
      const res = await appPageModelDetail({ code: this.row.code });
      if (res.code == 200) {
        const data = {};
        const list = [];
        const list_step4 = [];
        res.data?.queryFields?.forEach((item, index) => {
          item.idQueryFields = item.id;
          list.push({
            ...item,
            ...res.data?.resultFields[index],
            uuid: uuid.v1(),
            quHidden:item.quHidden ? item.quHidden : 'NO'
          });
        });
        res.data?.pageButtons?.forEach((item, index) => {
          list_step4.push({
            ...item,
            uuid: uuid.v1(),
            permissions: item.permissions
              ? JSON.parse(item.permissions)
              : undefined,
          });
        });
        data.step4 = list_step4;
        data.step2 = list;
        let cloneRes = JSON.parse(JSON.stringify(res.data));
        delete cloneRes.pageButtons;
        delete cloneRes.queryFields;
        delete cloneRes.resultFields;
        cloneRes = { ...cloneRes, dataSource: "1" };
        data.step1 = cloneRes;
        data.step5 = res.data?.pageVoDataRules;
        sessionStorage.setItem("pageModel", JSON.stringify(data));
        this.activeName = "1";
      }
      return;
    }
    if (this.row && this.modelType) {
      this.activeName = null;
      const res = await appPageModelDetail({ code: this.row.code });
      if (res.code == 200) {
        const data = {};
        const list = [];
        const list_step4 = [];
        res.data?.resultFields?.forEach((item) => {
          delete item.id;
          delete item.pageId;
        });
        res.data?.queryFields?.forEach((item, index) => {
          delete item.id;
          list.push({
            ...item,
            ...res.data?.resultFields[index],
            uuid: uuid.v1(),
          });
        });
        res.data?.pageButtons?.forEach((item) => {
          item.uuid = uuid.v1();
          item.permissions = item.permissions
            ? JSON.parse(item.permissions)
            : undefined;
          delete item.id;
          list_step4.push(item);
        });
        data.step4 = list_step4;
        data.step2 = list;
        let cloneRes = JSON.parse(JSON.stringify(res.data));
        delete cloneRes.pageButtons;
        delete cloneRes.queryFields;
        delete cloneRes.resultFields;
        delete cloneRes.id;
        cloneRes = { ...cloneRes, dataSource: "1" };
        data.step1 = cloneRes;
        sessionStorage.setItem("pageModel", JSON.stringify(data));
        this.activeName = "1";
      }
      return;
    }
  },
  methods: {
    handleDataConfigSum(value) {
      if (value.type === "date" && !value.dateType) {
        return this.$message.error("请选择日期时间格式化");
      }

      if (value.type === "dic" && !value.dict) {
        return this.$message.error("请选择数据字典");
      }

      if (
        value.type === "custom" &&
        (!value.customParams)
      ) {
        return this.$message.error("请选择接口");
      }
      let saveData = undefined;
      if (value.type === "date") {
        saveData = value.dateType;
      }
      if (value.type === "dic") {
        saveData = value.dictObj;
      }
      if (value.type === "custom") {
        saveData = JSON.stringify(value.customParams);
      }
       if (value.type === "customLogic") {
        saveData = value.optJs
      }
      this.$refs.listView.getConfigData(value.type, saveData);
    },
    handleDataConfigSumSearch(value) {
      if (
        (value.type === "input-date" || value.type === "input-date-range") &&
        !value.dateTypeFormat &&
        !value.datQ
      )
        return this.$message.error("请选择日期时间格式化或类型");
      if (value.type === "dic" && !value.dict)
        return this.$message.error("请选择数据字典");
      if (value.type === "dic" && !value.multiple)
        return this.$message.error("请选择是否多选");
         if (value.type === "custom" &&(!value.customParams)) {
        return this.$message.error("请选择接口");
      }
      if (value.type === "input-date" || value.type === "input-date-range") {
        this.$refs.queryCriteria.getConfigData(value.type, value);
      }
      if (value.type === "dic") {
        this.$refs.queryCriteria.getConfigData(value.type, {...value.dictObj,multiple:value.multiple});
      }
      if (value.type === "dept" || value.type === "user") {
        this.$refs.queryCriteria.getConfigData(value.type, value);
      }
       if (value.type === "custom") {
        this.$refs.queryCriteria.getConfigData(value.type, JSON.stringify(value.customParams),{multiple:value.multiple});
      }
    },
    buttonConfigSum(value) {
      if (value.type === "handleExt") {
         if(!value?.optJs) return this.$message.error('请填写操作逻辑')
        this.$refs.buttonConfig.getConfigData(value.type, {
          optJs: value.optJs,
          zdyLxb: value.zdyLxb,
        });
      }
      if (value.type === "zb") {
        if(!value?.zbCode) return this.$message.error('请选择页面模型')
        this.$refs.buttonConfig.getConfigData(value.type, {
          zbCode: value?.zbCode,
          cnSm: JSON.stringify(value?.cnSm),
          zbDisplayButton: value?.zbDisplayButton,
        });
      }
      if(value.type === "handleDel"){
         this.$refs.buttonConfig.getConfigData(value.type, {
          optJs: value?.deleteBeforeUrl,
        });
      } 
    },
    dataConfigClose() {
      this.dataConfigOpen = false;
    },
    dataConfigOpenFun(rowData) {
      this.dataConfigOpen = true;
      this.rowData = rowData;
    },
    searchDataConfigClose() {
      this.searchDataConfigOpen = false;
    },
    searchDataConfigOpenFun(rowData) {
      this.searchDataConfigOpen = true;
      this.rowSearchData = rowData;
    },
    buttonConfigOpenFun(rowData) {
      this.buttonConfigOpen = true;
      this.buttonConfigRow = rowData;
    },
    buttonConfigClose() {
      this.buttonConfigOpen = false;
    },

    handleClick(value) {
      const data = {
        ...JSON.parse(sessionStorage.getItem("pageModel")),
      };
      data.step1 = this.$refs.basicInformation?.form || data.step1;
      data.step2 =
        this.$refs.listView?.list_step1 ||
        this.$refs.queryCriteria?.list_step1 ||
        data.step2;
      data.step4 = this.$refs.buttonConfig?.list_step1 || data.step4;
      data.step5 = this.$refs.dataPower?.dataArr || data.step5;
      sessionStorage.setItem("pageModel", JSON.stringify(data));
    },
    closeConfirm() {
      this.close();
      sessionStorage.removeItem("pageModel");
    },
    async getChooseTableList() {
      this.loading = true;
      const res = await getOnlineList({
        ...this.queryParams,
        appId: this.appId,
      });
      if (res.code == 200) {
        this.tableData = res.rows;
        this.total = res.total;
      }
      this.loading = false;
    },
    async getChooseTableListForm() {
      this.loading = true;
      const res = await listAppInfo({
        ...this.queryParamsForm,
        appId: this.appId,
      });
      if (res.code == 200) {
        this.tableDataForm = res.rows;
        this.totalForm = res.total;
      }
      this.loading = false;
    },
    handleChooseTableSubmit() {
      if (!Object.keys(this.chooseData).length)
        return this.$message.error("请选择表数据");
      this.$refs.basicInformation.getChoostTableData(this.chooseData);
    },
    handleChooseTableSubmitForm() {
      if (!Object.keys(this.chooseDataForm).length)
        return this.$message.error("请选择表单数据");
      this.$refs.buttonConfig.getChoostTableData(this.chooseDataForm);
    },
    getCurrentRow(key) {
      this.chooseData = key;
    },
    getCurrentRowForm(key) {
      this.chooseDataForm = key;
    },
    async handleSubmit() {
      const data = {
        ...JSON.parse(sessionStorage.getItem("pageModel")),
      };
      data.step1 = this.$refs.basicInformation?.form || data.step1;
      data.step2 =
        this.$refs.listView?.list_step1 ||
        this.$refs.queryCriteria?.list_step1 ||
        data.step2;
      data.step2?.forEach((item, index) => {
        item.sort = index + 1;
        if (!item.sortable) {
          item.sortable = "YES";
        }
      });
      data.step4 = this.$refs.buttonConfig?.list_step1 || data.step4;
      data.step5 = this.$refs.dataPower?.dataArr || data.step5;
      sessionStorage.setItem("pageModel", JSON.stringify(data));
      if (!data.step1.name || !data.step1.code) {
        this.activeName = "1";
        setTimeout(() => {
          this.$refs.basicInformation?.handleSubmitBasicInformation();
        }, 500);
        return;
      }
      if (data.step2?.length === 0) {
        this.activeName = "2";
        return this.$message.error("至少一条列表显示信息");
      }
      if (data.step2?.length === 0) {
        this.activeName = "2";
        return this.$message.error("至少一条列表显示信息");
      }
      let isPass = true;
      for (let i = 0; i < data.step2?.length; i++) {
        if (!data.step2[i]?.field) {
          this.activeName = "2";
          this.$message.error(`序号为${i + 1}的列标识不能为空`);
          isPass = false;
          break;
        }
        if (!data.step2[i]?.label) {
          this.activeName = "2";
          this.$message.error(`序号为${i + 1}的列名称不能为空`);
          isPass = false;
          break;
        }
        if (!data.step2[i]?.type) {
          this.activeName = "2";
          this.$message.error(`序号为${i + 1}的列类型不能为空`);
          isPass = false;
          break;
        }
      }
      if (!isPass) {
        return;
      }
      let isPass_step4 = true;
      for (let i = 0; i < data.step4?.length; i++) {
        if (!data.step4[i]?.buttonType) {
          this.activeName = "4";
          this.$message.error(`序号为${i + 1}的操作类型不能为空`);
          isPass_step4 = false;
          break;
        }
        if (!data.step4[i]?.label) {
          this.activeName = "4";
          this.$message.error(`序号为${i + 1}的按钮名称不能为空`);
          isPass_step4 = false;
          break;
        }
      }
      if (!isPass_step4) {
        return;
      }
      const queryFields = [];
      data.step2?.forEach((item) => {
        queryFields.push({ ...item, id: item?.idQueryFields });
      });
      data.step4?.forEach((item, index) => {
        item.seq = index + 1;
        if (item.permissions?.length) {
          item.permissions = JSON.stringify(item.permissions);
        } else {
          item.permissions = undefined;
        }
      });
      const bodyParams = {
        ...data.step1,
        resultFields: data.step2,
        queryFields: queryFields,
        pageButtons: data.step4,
        pageDataRules: data.step5,
        appId: this.appId,
      };
      if (this.row && !this.modelType) {
        bodyParams.id = this.row?.id;
      }
      const res = await appPageModelSave(bodyParams);
      if (res.code == 200) {
        this.$message.success(
          this.row ? (this.modelType ? "复制成功" : "编辑成功") : "新增成功"
        );
        this.closeConfirm();
      }
    },
    handleCancel() {
      this.closeConfirm();
    },
  },
};
</script>

<style lang="scss" scoped>
.addOrEditModalMain {
  ::v-deep .addOrEditModal {
    .el-dialog__body {
      padding: 10px 20px;
      min-height: 85vh;
    }
  }
  ::v-deep .ChooseTable {
    .el-radio__label {
      display: none;
    }
    .input-with-select {
      width: 300px;
    }
    .el-icon-search {
      color: #fff;
    }
  }
}
</style>